package com.ushine.web.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ushine.web.base.mapper.UserAndUserGroupMapper;
import com.ushine.web.base.model.relation.UserAndUserGroupDO;
import com.ushine.web.base.service.IUserAndUserGroupService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: yls
 * @Date: 2022/02/15 23:56
 * @Description: 用户和用户组数据
 * @Version 1.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserAndUserGroupServiceImpl extends ServiceImpl<UserAndUserGroupMapper, UserAndUserGroupDO>
        implements IUserAndUserGroupService {

    @Override
    public Boolean insertBatchUserAndUserGroups(List<UserAndUserGroupDO> userAndUserGroups) {
        userAndUserGroups = Optional.ofNullable(userAndUserGroups).orElse(new ArrayList<>(0));
        Set<Long> userIds = userAndUserGroups.stream().map(UserAndUserGroupDO::getUserId).collect(Collectors.toSet());
        LambdaQueryWrapper<UserAndUserGroupDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(UserAndUserGroupDO::getUserId, userIds);
        remove(lambdaQueryWrapper);
        return saveBatch(userAndUserGroups);
    }

    @Override
    @Transactional(readOnly = true)
    public List<UserAndUserGroupDO> listUserAndUsrGroup(Long userId) {
        LambdaQueryWrapper<UserAndUserGroupDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserAndUserGroupDO::getUserId, userId)
                .select(UserAndUserGroupDO::getUserGroupId);
        return Optional.ofNullable(list(lambdaQueryWrapper)).orElse(new ArrayList<>(0));
    }
}
